﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Collections;
using System.Reflection;
using UMC.Web;
using UMC.Data.Entities;
using UMC.Web.UI;
using UMC.Proxy.Entities;
using UMC.Net;
using UMC.Data;

namespace UMC.Proxy.Activities
{
    /// <summary>
    /// 邮箱账户
    /// </summary>
    [UMC.Web.Mapping("Proxy", "Setup", Auth = WebAuthType.Admin)]
    class SiteSetupActivity : WebActivity
    {

        public override void ProcessActivity(WebRequest request, WebResponse response)
        {
            var ConfKey = this.AsyncDialog("ConfKey", r =>
            {
                return new Web.UISheetDialog() { Title = "新发布类型" }
                .Put("Web应用", "Proxy").Put("文件应用", "File");
            });
            if (ConfKey.StartsWith("https://") || ConfKey.StartsWith("http://"))
            {
                var url = new Uri(ConfKey);
                request.Arguments.Put("Domain", new Uri(url, "/").AbsoluteUri);
                ConfKey = url.LocalPath.Trim('/');
                if (String.IsNullOrEmpty(ConfKey))
                {
                    ConfKey = "Proxy";
                }
            }
            var secret = UMC.Data.WebResource.Instance().Provider["appSecret"];

            var config = this.AsyncDialog("Settings", g =>
            {
                var from = new Web.UIFormDialog() { Title = "发布新应用" };
                var sDomain = this.AsyncDialog("Domain", "none");

                switch (ConfKey)
                {
                    case "Self":
                        if (String.IsNullOrEmpty(secret))
                        {
                            this.Prompt("未注册");
                        }
                        else
                        {
                            UMC.Proxy.Utility.Sign(new Uri(APIProxy.Uri, "Transfer").WebRequest(), secret).Post(new WebMeta().Put("type", "Login", "SessionKey", Utility.Guid(Context.Token.Device.Value))).ReadAsString();

                            response.Redirect(new WebMeta("SessionKey", Utility.Guid(Context.Token.Device.Value)));
                        }
                        break;

                    case "UMC":
                    case "Proxy":
                    case "Bridge":
                        if (String.Equals(sDomain, "none"))
                        {
                            from.AddText("应用网址", "Domain", String.Empty);
                            this.Context.Request.Arguments.Remove("Domain");
                        }
                        else
                        {
                            from.AddTextValue().Put("应用网址", sDomain);
                        }
                        from.AddText("应用标识", "Root", String.Empty).PlaceHolder("[a-z0-9]全小写字符").Put("tip", $"将以[标识]为前缀合成域名来访问");
                        from.AddText("应用名称", "Caption", String.Empty);
                        break;

                    case "File":
                        this.Context.Request.Arguments.Remove("Domain");
                        from.Title = "发布文件应用";
                        from.AddOption("所在目录", "Domain", String.Empty, String.Empty).Command("System", "Dir", new WebMeta().Put("type", "Dir"));

                        from.AddText("应用标识", "Root", String.Empty).PlaceHolder("[a-z0-9]全小写字符").Put("tip", $"将以[标识]为前缀合成域名来访问");
                        from.AddText("应用名称", "Caption", String.Empty);
                        from.AddCheckBox("", "AuthConf", "none").Put("支持目录浏览", "*", true);
                        break;
                    default:
                        if (String.IsNullOrEmpty(secret))
                        {
                            this.Prompt("当前版本未登记注册", false);
                            this.Context.Response.Redirect("System", "License");
                        }
                        var webr2 = new Uri(APIProxy.Uri, "Transfer").WebRequest();
                        UMC.Proxy.Utility.Sign(webr2, secret);
                        var data = JSON.Deserialize<System.Collections.Hashtable>(webr2.Post(new WebMeta().Put("type", "Market", "ProductCode", ConfKey)).ReadAsString());

                        if (data.ContainsKey("success"))
                        {
                            if (data.ContainsKey("Domain"))
                            {
                                sDomain = data["Domain"] as string;
                                this.Context.Request.Arguments.Put("Domain", sDomain);
                                from.AddTextValue().Put("Saas网址", sDomain);

                            }
                            else if (String.Equals(sDomain, "none"))
                            {
                                from.AddText("应用网址", "Domain", String.Empty);
                                this.Context.Request.Arguments.Remove("Domain");
                            }
                            else
                            {
                                from.AddTextValue().Put("应用网址", sDomain);
                            }
                            from.AddText("应用标识", "Root", String.Empty).PlaceHolder("[a-z0-9]全小写字符").Put("tip", $"将以[标识]为前缀合成域名来访问");
                            from.AddText("应用名称", "Caption", data["Caption"] as string);

                            from.Submit("确认发布", "Site.Config");
                            from.Add(UICell.UI('\uf085', "提供者", data["Seller"] as string));
                            from.Add(UICell.UI('\ue94d', "服务电话", "", UIClick.Tel(data["Tel"] as string)));
                            return from;
                        }
                        else if (data.ContainsKey("BuySrc"))
                        {
                            from.Title = data["Title"] as string ?? "订购安装配置";
                            this.Context.Request.Arguments["API"] = data["BuySrc"] as string;
                            var Combo = data["Combo"] as Array;
                            var style = new UIStyle();
                            style.Name("icon").Color(0x09bb07).Size(84).Font("wdk");
                            style.Name("title").Color(0x333).Size(20);
                            style.BgColor(0xfafcff).Height(200).AlignCenter();
                            var desc = new UMC.Web.WebMeta().Put("title", data["Desc"] ?? "订购安装配置").Put("icon", data["Icon"] ?? "\uf085");
                            from.Config.Put("Header", new UIHeader().Desc(desc, "{icon}\n{title}", style));


                            from.AddTextValue().Put("所属应用", data["Caption"] as string ?? ConfKey).Put("服务提供者", data["Seller"] as string);

                            var f = from.AddRadio("订购套餐", "Combo");
                            var cl = Combo.Length;
                            for (var i = 0; i < cl; i++)
                            {
                                var hash = Combo.GetValue(i) as System.Collections.Hashtable;
                                f.Put(hash["Text"] as string, hash["Value"] as string, i == cl - 1);
                            }
                            from.Config.Put("Action", true);

                            from.Submit(data["Button"] as string ?? "确认订购");

                            return from;
                        }
                        else
                        {
                            this.Prompt("参数不正确");
                        }
                        break;
                }
                from.Submit("确认发布", "Site.Config");
                return from;
            });
            if (config.ContainsKey("API"))
            {
                var Combo = config["Combo"];
                var src = config["API"];
                this.Context.Response.Redirect(new Uri($"{src}&Combo={Combo}&Code={ConfKey}"));
            }

            var site = new Site();
            site.Root = config["Root"].ToLower();
            if (System.Text.RegularExpressions.Regex.IsMatch(site.Root, "^[a-z0-9]+$") == false)
            {
                this.Prompt("应用标识只支持【a-z0-9】字符");
            }
            site.Caption = config["Caption"];
            Uri Domain;
            try
            {
                Domain = new Uri(config["Domain"]);
                switch (Domain.Scheme)
                {
                    case "http":
                    case "https":
                        site.Domain = new Uri(Domain, "/").AbsoluteUri;
                        site.AuthConf = "*";
                        break;
                    case "file":
                        site.Domain = Domain.AbsoluteUri.TrimEnd('/');

                        if (config["AuthConf"].Contains("*"))
                        {
                            site.Domain += "/";
                        }
                        break;
                    default:
                        this.Prompt("网址格式不支持");
                        break;
                }
            }
            catch
            {
                this.Prompt("应用网址格式不正确");
                return;
            }

            site.SiteKey = UMC.Data.Utility.IntParse(UMC.Data.Utility.Guid(site.Root, true).Value);


            site.IsDesktop = true;
            var oldSite = DataFactory.Instance().Site(site.Root);
            if (oldSite != null)
            {
                if (oldSite.Flag == -1)
                {
                    this.AsyncDialog("Confirm", g => new Web.UIConfirmDialog("此标识存在于移除应用中，是否恢复此应用") { Title = "应用提示" });

                    DataFactory.Instance().Put(new Site { Root = site.Root, Flag = 0 });
                    this.Context.Send("Site.Config", false);
                    this.Context.Response.Redirect(this.Context.Request.Model, this.Context.Request.Command, site.Root);


                }
                else
                {
                    switch (ConfKey)
                    {
                        case "UMC":
                        case "Bridge":
                        case "File":
                        case "Proxy":
                            this.Prompt("此应用标识已注册");
                            break;
                        default:
                            this.AsyncDialog("Confirm", g => new Web.UIConfirmDialog($"确认在{oldSite.Caption}安装此应用配置，将有覆盖现有配置") { Title = "应用提示" });
                            break;
                    }
                }
            }
            else
            {
                if (String.IsNullOrEmpty(secret) == false)
                {
                    UMC.Proxy.Utility.Sign(new Uri(APIProxy.Uri, "Certificater").WebRequest(), secret).Post(new WebMeta().Put("type", "site", "domain", site.Root), r => { });
                }
                String webrkey = String.Format("images/{0}/{1}/{2}.png", site.Root, 1, 0);
                using (System.IO.Stream stream = typeof(WebServlet).Assembly//UMC.Proxy
                                        .GetManifestResourceStream("UMC.Proxy.Resources.app.png"))
                {
                    UMC.Data.WebResource.Instance().Transfer(stream, webrkey);
                }
            }
            switch (ConfKey)
            {
                case "Proxy":
                    site.AuthConf = "*";
                    site.AuthType = WebAuthType.All;
                    break;
                case "File":
                    site.AuthType = WebAuthType.All;
                    break;
                case "UMC":
                    site.AuthConf = "#";
                    site.UserModel = UserModel.Bridge;
                    site.AuthType = WebAuthType.Guest;
                    break;
                case "Bridge":
                    site.AuthConf = "";
                    site.UserModel = UserModel.Bridge;
                    site.AuthType = WebAuthType.Guest;
                    break;

                default:
                    var json = UMC.Proxy.Utility.Sign(new Uri(APIProxy.Uri, "Transfer").WebRequest(), secret).Post(new WebMeta().Put("type", "Market", "ConfKey", ConfKey)).ReadAsString();


                    var data = JSON.Deserialize<System.Collections.Hashtable>(json);
                    if (data.ContainsKey("success"))
                    {
                        var appConf = data["appConf"] as Hashtable;
                        appConf.Remove("Root");
                        appConf.Remove("Domain");
                        appConf.Remove("Caption");
                        UMC.Data.Reflection.SetProperty(site, appConf);
                        if (data.ContainsKey("Src"))
                        {
                            UMC.Data.WebResource.Instance().Transfer(new Uri(data["Src"] as string), $"images/{site.Root}/1/0.png");
                        }
                        if (data.ContainsKey("Domain"))
                        {
                            site.Domain = data["Domain"] as String;
                        }

                        site.IsMarket = true;
                        var appendJSConf = appConf["appendJsConf"] as Hashtable;
                        if (appendJSConf != null)
                        {
                            var em = appendJSConf.GetEnumerator();

                            var jsConf = new System.Text.StringBuilder();
                            while (em.MoveNext())
                            {
                                jsConf.Append(em.Key);
                                jsConf.AppendLine();

                                Config pconfig = new Config();
                                var md5Key = SiteActivity.MD5(em.Key as string);

                                pconfig.ConfKey = String.Format("SITE_JS_CONFIG_{0}{1}", site.Root, md5Key).ToUpper();
                                pconfig.ConfValue = em.Value as string;
                                UMC.Data.DataFactory.Instance().Put(pconfig);


                            }
                            site.AppendJSConf = jsConf.ToString();
                        }
                        var configImage = appConf["confImage"] as Hashtable;
                        if (configImage != null)
                        {
                            var em = configImage.GetEnumerator();

                            var jsConf = new System.Text.StringBuilder();
                            while (em.MoveNext())
                            {
                                jsConf.Append(em.Key);
                                jsConf.AppendLine();

                                Config pconfig = new Config();
                                var md5Key = SiteActivity.MD5(em.Key as string);

                                pconfig.ConfKey = String.Format("SITE_IMAGE_CONFIG_{0}{1}", site.Root, md5Key).ToUpper();
                                pconfig.ConfValue = JSON.Serialize(em.Value);
                                UMC.Data.DataFactory.Instance().Put(pconfig);


                            }
                            site.ImagesConf = jsConf.ToString();
                        }
                        if (appConf.ContainsKey("loginHtml"))
                        {
                            Config pconfig = new Config();
                            pconfig.ConfKey = $"SITE_MIME_{site.Root}_LOGIN_HTML".ToUpper();
                            pconfig.ConfValue = appConf["loginHtml"] as string;
                            UMC.Data.DataFactory.Instance().Put(pconfig);
                        }
                        if (appConf.ContainsKey("login"))
                        {
                            CopyMime(appConf["login"] as Hashtable, $"SITE_MIME_{site.Root}_LOGIN".ToUpper());
                        }
                        if (appConf.ContainsKey("check"))
                        {
                            CopyMime(appConf["check"] as Hashtable, $"SITE_MIME_{site.Root}_CHECK".ToUpper());
                        }
                        if (appConf.ContainsKey("update"))
                        {
                            CopyMime(appConf["update"] as Hashtable, $"SITE_MIME_{site.Root}_UPDATE".ToUpper());
                        }
                        Save(site);

                    }
                    else
                    {
                        this.Prompt("提示", data["msg"] as string ?? "导入配置错误");
                    }

                    break;
            }
            Save(site);

        }
        void Save(Site site)
        {
            site.AppSecret = Utility.Guid(Guid.NewGuid());
            DataFactory.Instance().Put(site);
            this.Prompt("发布应用成功", false);
            this.Context.Send("Site.Config", false);
            if (site.UserModel == UserModel.Bridge && String.Equals(site.AuthConf, "#"))
            {
                new Uri(new Uri(site.Domain), "/UMC.Conf").WebRequest().Put(new WebMeta().Put("authSecret", site.AppSecret).Put("domain", $"{Web.WebResource.Instance().WebDomain()}"), r =>
                {

                });
                this.Context.Response.Redirect(this.Context.Request.Model, "UMC", site.Root);
            }
            else
            {
                this.Context.Response.Redirect(this.Context.Request.Model, "Site", site.Root);
            }
        }
        void CopyMime(Hashtable config, String key)
        {
            var array = config["Feilds"] as Hashtable;
            var fConfig = new Hashtable();
            if (array != null)
            {
                var em = array.GetEnumerator();
                while (em.MoveNext())
                {
                    var fConf = em.Value as Hashtable;
                    fConfig[em.Key] = fConf["Caption"];
                    fConf.Remove("Caption");
                    if (fConf.Count > 0)
                    {
                        var fconfig2 = new Config();
                        fconfig2.ConfKey = $"{key}_{em.Key}".ToUpper();
                        fconfig2.ConfValue = JSON.Serialize(fConf);
                        UMC.Data.DataFactory.Instance().Put(fconfig2);
                    }
                }
                config["Feilds"] = fConfig;
            }

            var fconfig = new Config();
            fconfig.ConfKey = key.ToUpper();
            fconfig.ConfValue = JSON.Serialize(config);
            UMC.Data.DataFactory.Instance().Put(fconfig);



        }
    }
}